<?php

namespace Biz\service\adCalendar;

use Biz\model\advertisement\MHhzAdmin;
use Biz\model\advertisement\MHhzDepartment;
use Biz\model\advertisement\MPositionAdType;
use Biz\model\advertisement\MPositionProject;
use Biz\model\advertisement\MPositionProjectRelations;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class AdPositionCalendarExport
{

    const EXPORT_DATA_TYPE_POS = 1; //资源位维度

    const EXPORT_DATA_TYPE_PROJECT = 2; //项目维度

    //导出数据维度
    const EXPORT_DATA_TYPES = [
        self::EXPORT_DATA_TYPE_POS => '资源位维度',
        self::EXPORT_DATA_TYPE_PROJECT => '项目维度',
    ];

    //是否共享
    const SHARE_STATUS = [
        MPositionProjectRelations::SHARE_OK => '共享',
        MPositionProjectRelations::SHARE_NO => '不共享',
    ];

    //占位状态
    const PROJECT_STATUS = [
        MPositionProjectRelations::PROJECT_STATUS_OK => '正常',
        MPositionProjectRelations::PROJECT_STATUS_RELEASE => '已释放',
    ];

    //占位状态
    const SOLD_STATUS = [
        MPositionProject::PRE_SOLD_STATUS => '预占位',
        MPositionProject::SOLD_STATUS => '已下单',
    ];

    private static $departmentId;

    private static $exportDataType;

    private static $startTime;

    private static $endTime;

    private static function getDataByPos()
    {
        $data = MPositionAdType::select(
            [
                "[<]" . MPositionProjectRelations::_TABLE_NAME => ["id" => "ad_id"],
                "[>]" . MPositionProject::_TABLE_NAME => [MPositionProjectRelations::_TABLE_NAME . ".project_id" => "id"],
                "[>]" . MHhzAdmin::_TABLE_NAME => [MPositionProject::_TABLE_NAME . ".admin_id" => "id"],
                "[>]" . MHhzDepartment::_TABLE_NAME => [MPositionProject::_TABLE_NAME . ".department_id" => "id"],
            ],
            [
                MPositionProjectRelations::_TABLE_NAME . ".id",
                MPositionProjectRelations::_TABLE_NAME . ".ad_id",
                MPositionProjectRelations::_TABLE_NAME . ".department_id",
                MPositionProjectRelations::_TABLE_NAME . ".project_id",
                MPositionProjectRelations::_TABLE_NAME . ".start_show_time",
                MPositionProjectRelations::_TABLE_NAME . ".end_show_time",
                MPositionProjectRelations::_TABLE_NAME . ".is_share",
                MPositionProjectRelations::_TABLE_NAME . ".is_exclusive",
                MPositionProjectRelations::_TABLE_NAME . ".ad_unique",
                MPositionProjectRelations::_TABLE_NAME . ".project_status",
                MPositionProject::_TABLE_NAME . ".project_name",
                MPositionProject::_TABLE_NAME . ".is_sold",
                MHhzAdmin::_TABLE_NAME . ".account",
                MHhzAdmin::_TABLE_NAME . ".username",
                MHhzDepartment::_TABLE_NAME . ".name",
                MPositionAdType::_TABLE_NAME . ".type_name",
                MPositionAdType::_TABLE_NAME . ".type_status",
            ],
            [
                MPositionProjectRelations::_TABLE_NAME . ".department_id" => self::$departmentId,
                MPositionProjectRelations::_TABLE_NAME . ".project_status" => MPositionProjectRelations::PROJECT_STATUS_OK,
                MPositionProjectRelations::_TABLE_NAME . ".start_show_time[<=]" => self::$endTime,
                MPositionProjectRelations::_TABLE_NAME . ".end_show_time[>=]" => self::$startTime,
                MPositionProject::_TABLE_NAME . ".project_status" => MPositionProject::PROJECT_STATUS_OK,

            ]
        );

        $data = $data && is_array($data) ? $data : [];

        $exportHeader = [
            'date' => '日期',
            'type_name' => '资源位名称',
            'project_name' => '占位项目名称',
            'is_share' => '是否共享',
            'ad_unique' => '关键词',
            'username' => '占位人',
            'department_name' => '部门',
            'is_sold' => '占位状态'
        ];

        $exportData = [];

        foreach ($data as $key => $v) {
            $startShowTimeStamp = strtotime(date('Y-m-d', strtotime($v['start_show_time'])));
            $endShowTimeStamp = strtotime(date('Y-m-d', strtotime($v['end_show_time'])));
            for ($t = $startShowTimeStamp; $t <= $endShowTimeStamp; $t = strtotime('+1 day', $t)) {
                //超出时间范围的不导出
                if($t < strtotime(self::$startTime) || $t > strtotime(self::$endTime)){
                    continue;
                }
                $exportData[] = [
                    'date' => date('Y/m/d', $t),
                    'type_name' => $v['type_name'],
                    'project_name' => $v['project_name'],
                    'is_share' => self::SHARE_STATUS[$v['is_share']],
                    'ad_unique' => self::formatKeyWords($v['ad_unique']),
                    'username' => $v['username'],
                    'department_name' => $v['name'],
                    'project_status' => self::PROJECT_STATUS[$v['project_status']],
                    'ad_id' => $v['ad_id'],
                    'is_sold' => self::SOLD_STATUS[$v['is_sold']],
                ];
            }
        }

        $sortAdIdArr = array_column($exportData, 'ad_id');
        $sortDateArr = array_column($exportData, 'date');

        //先按ad_id排序，再按日期排序
        array_multisort($sortAdIdArr, SORT_ASC, SORT_NUMERIC, $sortDateArr, SORT_ASC, SORT_STRING, $exportData);

        return [$exportHeader, $exportData];
    }


    private static function getDataByProject()
    {
        $data = MPositionProjectRelations::select(
            [
                "[>]" . MPositionProject::_TABLE_NAME => ["project_id" => "id"],
                "[>]" . MPositionAdType::_TABLE_NAME => ["ad_id" => "id"],
                "[>]" . MHhzAdmin::_TABLE_NAME => [MPositionProject::_TABLE_NAME . ".admin_id" => "id"],
                "[>]" . MHhzDepartment::_TABLE_NAME => [MPositionProject::_TABLE_NAME . ".department_id" => "id"],
            ],
            [
                MPositionProjectRelations::_TABLE_NAME . ".id",
                MPositionProjectRelations::_TABLE_NAME . ".ad_id",
                MPositionProjectRelations::_TABLE_NAME . ".department_id",
                MPositionProjectRelations::_TABLE_NAME . ".project_id",
                MPositionProjectRelations::_TABLE_NAME . ".start_show_time",
                MPositionProjectRelations::_TABLE_NAME . ".end_show_time",
                MPositionProjectRelations::_TABLE_NAME . ".is_share",
                MPositionProjectRelations::_TABLE_NAME . ".is_exclusive",
                MPositionProjectRelations::_TABLE_NAME . ".ad_unique",
                MPositionProjectRelations::_TABLE_NAME . ".project_status",
                MPositionProject::_TABLE_NAME . ".project_name",
                MPositionProject::_TABLE_NAME . ".is_sold",
                MHhzAdmin::_TABLE_NAME . ".account",
                MHhzAdmin::_TABLE_NAME . ".username",
                MHhzDepartment::_TABLE_NAME . ".name",
                MPositionAdType::_TABLE_NAME . ".type_name",
                MPositionAdType::_TABLE_NAME . ".type_status",
            ],
            [
                MPositionProjectRelations::_TABLE_NAME . ".department_id" => self::$departmentId,
                MPositionProjectRelations::_TABLE_NAME . ".project_status" => MPositionProjectRelations::PROJECT_STATUS_OK,
                MPositionProjectRelations::_TABLE_NAME . ".start_show_time[<=]" => self::$endTime,
                MPositionProjectRelations::_TABLE_NAME . ".end_show_time[>=]" => self::$startTime,
                MPositionProject::_TABLE_NAME . ".project_status" => MPositionProject::PROJECT_STATUS_OK,
            ]);

        $data = $data && is_array($data) ? $data : [];

        $exportHeader = [
            'project_name' => '项目名称',
            'ad_type_name' => '资源位名称',
            'ad_time_range' => '起始时间',
            'is_share' => '是否共享',
            'ad_unique' => '关键词',
            'username' => '占位人',
            'department_name' => '部门',
            'is_sold' => '占位状态'
        ];

        $exportData = [];

        foreach ($data as $key => $v) {
            $exportData[$key] = [
                'project_name' => $v['project_name'],
                'ad_type_name' => $v['type_name'],
                'ad_time_range' => $v['start_show_time'] . ' - ' . $v['end_show_time'],
                'is_share' => self::SHARE_STATUS[$v['is_share']],
                'ad_unique' => self::formatKeyWords($v['ad_unique']),
                'username' => $v['username'],
                'department_name' => $v['name'],
                'is_sold' => self::SOLD_STATUS[$v['is_sold']],
                'project_status' => self::PROJECT_STATUS[$v['project_status']],
                'project_id' => $v['project_id'],
                'ad_id' => $v['ad_id'],
            ];
        }

        $sortProjectIdArr = array_column($exportData, 'project_id');
        $sortAdIdArr = array_column($exportData, 'ad_id');

        //先按项目排，再按资源位排序
        array_multisort($sortProjectIdArr, SORT_ASC, SORT_NUMERIC, $sortAdIdArr, SORT_ASC, SORT_NUMERIC, $exportData);

        return [$exportHeader, $exportData];

    }


    private static function formatKeyWords($keywords)
    {
        if (empty($keywords)) {
            return $keywords;
        }
        $keywords = trim($keywords, '-');
        $keywords = str_replace('/', ',', $keywords);
        $keywords = str_replace('、', ',', $keywords);
        $keywords = str_replace('，', ',', $keywords);
        $keywords = str_replace('-', ',', $keywords);
        return $keywords;
    }


    public static function export($departmentId, $exportDataType, $startTime, $endTime)
    {
        self::$departmentId = $departmentId;

        self::$exportDataType = $exportDataType;

        self::$startTime = date('Y-m-d 00:00:00', strtotime($startTime));

        self::$endTime = date('Y-m-d 23:59:59', strtotime($endTime));

        $exportHeader = $exportData = [];

        switch (self::$exportDataType) {
            case self::EXPORT_DATA_TYPE_POS:
                [$exportHeader, $exportData] = self::getDataByPos();
                break;
            case self::EXPORT_DATA_TYPE_PROJECT:
                [$exportHeader, $exportData] = self::getDataByProject();
                break;
        }

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('资源位日历-' . self::EXPORT_DATA_TYPES[$exportDataType]);
        $titCol = 'A';
        $valueKeys = [];
        foreach ($exportHeader as $key => $value) {
            $valueKeys[] = $key;
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        $sheet->getColumnDimension('A')->setWidth(40);
        $sheet->getColumnDimension('B')->setWidth(40);
        $sheet->getColumnDimension('C')->setWidth(40);
        $sheet->getColumnDimension('D')->setWidth(15);
        $sheet->getColumnDimension('E')->setWidth(50);
        $sheet->getColumnDimension('F')->setWidth(15);
        $sheet->getColumnDimension('G')->setWidth(30);
        $sheet->getColumnDimension('H')->setWidth(15);
        $row = 2; // 从第二行开始
        foreach ($exportData as $item) {
            $dataCol = 'A';
            foreach ($valueKeys as $field) {
                $value = isset($item[$field]) ? $item[$field] : '';
                $sheet->setCellValue($dataCol . $row, $value);
                $dataCol++;
            }
            $row++;
        }

        $fileName = date('Ymd') . '-资源位日历-' . self::EXPORT_DATA_TYPES[$exportDataType] . '.xlsx';

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

        exit;
    }
}